const util = require("../../../utils/util");

// pages/mails/address/address.js
Page({

      /**
       * 页面的初始数据
       */
      data: {
            // address: getApp().globalData.sendExpressData['currentCollectAddress'], // 页面展示的数据

            // 控件数据
            source: 0, // 用于判断是从哪里进入编辑页面的，0表示是从寄件进来，1表示从收件进来，2表示从地址簿进来。其他的都表示新建地址
            defaultAddress: false, // 设置默认地址
      },

      /**
       * 生命周期函数--监听页面加载
       */
      onLoad: function (options) {
            // console.log(options)
            this.setData({
                  source: options.source ? Number(options.source) : ''
            })
            this.initData(Number(options.source))
            // this.initData(0)
      },
      /* 初始化数据 */
      initData(source) {
            const app = getApp().globalData;
            const sendExpressData = app['sendExpressData'] ? app['sendExpressData'] : {}
            if (source === 0) {
                  this.setData({
                        // address: JSON.parse(JSON.stringify(sendExpressData['currentSenAddress']))         // 寄件人信息
                        address: Object.assign({}, sendExpressData['currentSenAddress']) // 寄件人信息
                  })
            } else if (source === 1) {
                  this.setData({
                        // address: sendExpressData['currentCollectAddress'] // 收件人信息
                        address: Object.assign({}, sendExpressData['currentCollectAddress']) // 寄件人信息
                  })
            } else if (source === 2) {

            } else { // 其他方式进入，则新建数据
                  this.setData({
                        address: {
                              "id": '', // 确认地址的唯一标识
                              "name": '', // 寄件人名称
                              "phone": '', //寄件人联系方式
                              "title": "", // 提示文字，详细地址
                              "defaultAddress": false, // 默认地址
                              "location": { // 解析到的坐标
                                    "lng": '', // 经度
                                    "lat": '' // 纬度
                              },
                              "ad_info": { // 行政区划信息
                                    "adcode": "" // 行政区划代码
                              },
                              "address_components": { // 解析后的地址部件
                                    "province": "", // 省
                                    "city": "", // 市
                                    "district": "", // 区，可能为空字串
                                    "street": "", // 街道，可能为空字串
                                    "street_number": "", // 门牌，可能为空字串
                                    "company": '', // 公司名称
                              },
                              "level": 9 // 解析精度级别，分为11个级别，一般>=9即可采用（定位到点，精度较高） 也可根据实际业务需求自行调整，完整取值表见下文。
                        }
                  })
            }
      },

      /* 提交 */
      confirmFn() {
            if (!(/^1[3456789]\d{9}$/.test(this.data.address.phone))) {
                  wx.showToast({
                        title: '电话格式错误，请重新输入',
                        icon: 'none'
                  })
            } else {
                  const app = getApp().globalData;
                  // const sendExpressData = app['sendExpressData'] ? app['sendExpressData'] : {}
                  if (this.data.source === 0) {
                        app['sendExpressData']['currentSenAddress'] = this.data.address;
                  } else if (this.data.source === 1) {
                        app['sendExpressData']['currentCollectAddress'] = this.data.address;
                  } else if (this.data.source === 2) {

                  }
                  wx.navigateBack({
                        delta: 0,
                  })
                  // console.log(app)
                  // console.log(this.data.address)
            }
      },

      /* 设置默认地址 */
      defaultAddressFn() {
            this.data.address['defaultAddress'] = !this.data.defaultAddress
            this.setData({
                  defaultAddress: !this.data.defaultAddress,
                  address: this.data.address
            })
      },

      // 清空信息
      reset(){
            this.data.address['defaultAddress'] = !this.data.defaultAddress
            let data = this.data.address
            data.name = ''
            data.phone = ''
            data.title = ''
            data.location['lat'] = ''
            data.location['lng'] = ''
            data['address_components']['province'] = ''
            data['address_components']['city'] = ''
            data['address_components']['district'] = ''
            data['address_components']['street'] = ''
            data['address_components']['street_number'] = ''
            data['address_components']['company'] = ''

            this.setData({
                  address: this.data.address
            })
      },

      /* 名字修改 */
      changeName(e) {
            let name = e.detail.value;
            this.data.address['name'] = name;
            this.setData({
                  address: this.data.address
            })
      },
      /* 电话修改 */
      changePhone(e) {
            let phone = e.detail.value;
            this.data.address['phone'] = phone;
            this.setData({
                  address: this.data.address
            })
            console.log(this.data.address)
      },
      /* 公司名称修改 */
      changeCompany(e) {
            let company = e.detail.value;
            this.data.address.address_components['company'] = company;
            this.setData({
                  address: this.data.address
            })
            // console.log(this.data.address)
      },

      /* 使用地图来选择地址 */
      mapAddress() {
            let this_ = this;
            // console.log(this.data.address['address_components']['district'])
            let district = this.data.address['address_components']['district']
            // console.log(district)
            if (!district) { // 如果为空，则使用当前位置
                  wx.getLocation({
                        success(res) {
                              // console.log(res)
                              let latitude = res.latitude
                              let longitude = res.longitude
                              wx.chooseLocation({
                                    latitude,
                                    longitude,
                                    success(res_) {
                                          // console.log('res_')
                                          // console.log(res_)
                                          if (!res_.name) {
                                                wx.showToast({
                                                      title: '必须选中一条地址',
                                                      icon: 'none'
                                                })
                                                return;
                                          }
                                          util.v1({
                                                location: latitude + "," + longitude,
                                                success(res) {
                                                      // console.log('res==-===')
                                                      // console.log(res)
                                                      let data = res.data['result']['address_component']
                                                      this_.data.address['title'] = res_.name;
                                                      this_.data.address['address_components']['province'] = data['province'];
                                                      this_.data.address['address_components']['city'] = data['city'];
                                                      this_.data.address['address_components']['district'] = data['district'];
                                                      this_.data.address['location']['lat'] = latitude;
                                                      this_.data.address['location']['lng'] = longitude;
                                                      this_.setData({
                                                            address: this_.data.address
                                                      })
                                                }
                                          })
                                    }
                              })
                        }
                  })
            } else {
                  if (!this_.data.address['location']['lat']) {
                        util.suggestion({
                              keyword: district,
                              region: '广东',
                              success(res) {
                                    // console.log('=005=-3495-')
                                    // console.log(res)
                                    if (res.data.data.length > 0) {
                                          let location = res.data.data[0]['location']
                                          wx.chooseLocation({
                                                latitude: location.lat,
                                                longitude: location.lng,
                                                success(res) {
                                                      // console.log('1111111111')
                                                      // console.log(res)
                                                      this_.data.address['title'] = res.name;
                                                      this_.data.address['location']['lat'] = res.latitude;
                                                      this_.data.address['location']['lng'] = res.lng;
                                                      this_.setData({
                                                            address: this_.data.address
                                                      })
                                                }
                                          })
                                    }
                              }
                        })
                  } else {
                        wx.chooseLocation({
                              latitude: this_.data.address['location']['lat'],
                              longitude: this_.data.address['location']['lng'],
                              success(res) {
                                    // console.log('1111111111')
                                    // console.log(res)
                                    this_.data.address['title'] = res.name;
                                    this_.data.address['location']['lat'] = res.latitude;
                                    this_.data.address['location']['lng'] = res.lng;
                                    this_.setData({
                                          address: this_.data.address
                                    })
                              }
                        })
                  }
            }
      },
      // 跳转到新的页面选择地址
      detailAddr(e) {
            let address = e.currentTarget.dataset.addr;
            if (!address) return;
            let this_ = this;
            // console.log(address)
            wx.navigateTo({
                  url: address,
                  events: {
                        // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
                        acceptDataFromOpenedPage: function (data) {
                              // console.log(data)
                              this_.setData({
                                    address: data.data
                              })
                        }
                  },
                  success: function (res) {
                        // 通过eventChannel向被打开页面传送数据
                        res.eventChannel.emit('acceptDataFromOpenerPage', {
                              data: this_.data.address
                        })
                  }
            })
      },
      // 跳转到地址簿页面
      choolAddressBook(e) {
            let this_ = this;
            let address = e.currentTarget.dataset.addr;
            let type = e.currentTarget.dataset.type;
            if (!address) return;
            console.log(address)
            wx.navigateTo({
                  url: address,
                  events: {
                        // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
                        acceptDataFromOpenedPage: function (res) {
                              // console.log(res)
                              this_.setData({
                                    address: res.data
                              })
                        }
                  },
                  success: function (res) {
                        // 通过eventChannel向被打开页面传送数据
                        res.eventChannel.emit('acceptDataFromOpenerPage', {
                              "type": type
                        })
                  }
            })
      },

      // 选择完城市
      bindReginChange(e) {
            // console.log(e)
            var [province, city, district] = e.detail.value;
            this.data.address.address_components['province'] = province
            this.data.address.address_components['city'] = city
            this.data.address.address_components['district'] = district
            this.data.address['title'] = ''
            this.setData({
                  address: this.data.address
            })
            // console.log(this.data.address)
      },

      /**
       * 生命周期函数--监听页面初次渲染完成
       */
      onReady: function () {

      },

      /**
       * 生命周期函数--监听页面显示
       */
      onShow: function () {

      },

      /**
       * 生命周期函数--监听页面隐藏
       */
      onHide: function () {

      },

      /**
       * 生命周期函数--监听页面卸载
       */
      onUnload: function () {

      },

      /**
       * 页面相关事件处理函数--监听用户下拉动作
       */
      onPullDownRefresh: function () {

      },

      /**
       * 页面上拉触底事件的处理函数
       */
      onReachBottom: function () {

      },

      /**
       * 用户点击右上角分享
       */
      onShareAppMessage: function () {

      }
})